<template>
  <el-dialog
    :title="dialogTitle"
    width="400px"
    class="addModuleFlex"
    @close="closeDialog"
  >
    <el-form
      ref="moduleForm"
      :model="moduleForm"
      label-position="top"
      :rules="addModuleRules"
    >
      <div>
        <el-form-item :label="$t('modules.contract.plat')" prop="platCode">
          <el-select
            v-model="moduleForm.platCode"
            :disabled="isEdit && moduleForm.feeOccur"
            clearable
            @change="changePlateCode"
            class="w-full"
          >
            <el-option
              v-for="item in platOptions"
              :key="item.value"
              :label="$t('contract_plat.' + item.value)"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <div>
        <el-form-item prop="billingServiceCode">
          <template #label>
            {{ $t("modules.contract.billing_method") }}
          </template>
          <el-select
            v-model="moduleForm.billingServiceCode"
            :disabled="isEdit && moduleForm.feeOccur"
            clearable
            @change="changeStatisticMethod"
            class="w-full"
          >
            <el-option
              v-for="item in currentPlatOption.billingServiceList"
              :key="item.value"
              :label="$t('flycare.billing_service.' + item.value + '.name')"
              :value="item.value"
            />
          </el-select>
          <el-tag
            v-if="currentServiceOption"
            type="warning"
            class="service_tip"
            v-html="$t('flycare.billing_service.' + currentServiceOption.value + '.tip')"
          />
        </el-form-item>
      </div>
      <el-form-item
        v-if="formItemShow('price')"
        id="priceInput"
        :label="$t('modules.contract.price')"
        prop="price"
      >
        <el-input
          v-model="moduleForm.price"
          style="width: 100%; margin-top: 5px"
          :disabled="moduleForm.feeOccur"
          @blur="() => (moduleForm.price = moduleForm.price.trim())"
        >
          <template #append>
            <span>
              {{
                $t(
                  "flycare.billing_service." + currentServiceOption.value + ".price_unit"
                )
              }}
            </span></template
          >
        </el-input>
      </el-form-item>

      <el-form-item
        v-if="formItemShow('serviceAmount')"
        :label="
          $t('flycare.billing_service.' + currentServiceOption.value + '.amount_label')
        "
        prop="serviceAmount"
      >
        <el-input
          v-model="moduleForm.serviceAmount"
          :disabled="moduleForm.feeOccur"
          style="width: 100%; margin-top: 5px"
          @blur="() => (moduleForm.serviceAmount = moduleForm.serviceAmount.trim())"
        >
          <template #append>
            <span>
              {{
                $t(
                  "flycare.billing_service." + currentServiceOption.value + ".amount_unit"
                )
              }}
            </span></template
          >
        </el-input>
      </el-form-item>

      <el-form-item
        v-if="formItemShow('serviceQuantity')"
        :label="
          $t('flycare.billing_service.' + currentServiceOption.value + '.quantity_label')
        "
        prop="serviceQuantity"
      >
        <el-input
          v-model="moduleForm.serviceQuantity"
          :disabled="moduleForm.feeOccur"
          style="width: 100%; margin-top: 5px"
          @blur="() => (moduleForm.serviceQuantity = moduleForm.serviceQuantity.trim())"
        >
          <template #append>
            <span>
              {{
                $t(
                  "flycare.billing_service." +
                    currentServiceOption.value +
                    ".quantity_unit"
                )
              }}
            </span></template
          >
        </el-input>
      </el-form-item>

      <el-form-item
        v-if="formItemShow('serviceStartTime')"
        prop="serviceStartTime"
        :rules="{
          required: formItemRequired('serviceStartTime'),
          message: $t('modules.contract.service_start_time_require'),
          trigger: 'blur',
        }"
      >
        <template #label>
          {{
            $t(
              "flycare.billing_service." +
                currentServiceOption.value +
                ".start_time_label"
            )
          }}
          <el-tooltip
            class="item"
            effect="dark"
            :content="
              $t(
                'flycare.billing_service.' +
                  currentServiceOption.value +
                  '.start_time_tip'
              )
            "
            placement="top"
          >
            <svg-icon icon-class="explain" />
          </el-tooltip>
        </template>
        <el-date-picker
          v-model="moduleForm.serviceStartTime"
          :disabled="moduleForm.feeOccur"
          style="width: 100%"
          :format="'YYYY-MM'"
          :value-format="'timestamp'"
          type="month"
          clearable
          @change="changeServiceStartTime"
        />
        <el-tag
          v-show="!isEdit && !moduleForm.feeOccur"
          v-for="time in timeQuickSelect"
          :key="time.timestamp"
          size="small"
          style="margin-right: 5px; cursor: pointer"
          @click="quickSelectStartTime(time)"
        >
          {{ time.timeStr }}
        </el-tag>
      </el-form-item>
      <el-form-item
        v-if="formItemShow('serviceEndTime')"
        prop="serviceEndTime"
        :rules="{
          required: formItemRequired('serviceEndTime'),
          validator: serviceEndTimeValidator,
          trigger: 'blur',
        }"
      >
        <template #label>
          {{
            $t(
              "flycare.billing_service." + currentServiceOption.value + ".end_time_label"
            )
          }}
          <el-tooltip
            class="item"
            effect="dark"
            :content="
              $t(
                'flycare.billing_service.' + currentServiceOption.value + '.end_time_tip'
              )
            "
            placement="top"
          >
            <svg-icon icon-class="explain" />
          </el-tooltip>
        </template>
        <el-date-picker
          v-model="moduleForm.serviceEndTime"
          style="width: 100%"
          :format="'YYYY-MM'"
          :value-format="'timestamp'"
          size="small"
          type="month"
          :disabled="formItemDisabled('serviceEndTime')"
        />
      </el-form-item>
      <div v-if="formItemShow('freeNum')">
        <el-form-item prop="freeNum">
          <template #label>
            <span>
              <div style="margin-bottom: -20px; display: inline-block">
                {{
                  $t(
                    "flycare.billing_service." +
                      currentServiceOption.value +
                      ".free_num_label"
                  )
                }}
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="
                    $t(
                      'flycare.billing_service.' +
                        currentServiceOption.value +
                        '.free_num_tip'
                    )
                  "
                  placement="top"
                >
                  <svg-icon icon-class="explain" />
                </el-tooltip>
              </div> </span
          ></template>
          <!-- The quantity that can be free according to this billing method -->
          <el-input
            v-model="moduleForm.freeNum"
            :disabled="moduleForm.feeOccur"
            style="width: 100%"
            @input="changeFreeNum"
          />
        </el-form-item>
      </div>
      <div v-if="formItemShow('freeExpireTime')">
        <el-form-item prop="freeExpireTime">
          <template #label>
            <span>
              <div style="margin-bottom: -20px; display: inline-block">
                {{
                  $t(
                    "flycare.billing_service." +
                      currentServiceOption.value +
                      ".free_expire_time_label"
                  )
                }}
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="
                    $t(
                      'flycare.billing_service.' +
                        currentServiceOption.value +
                        '.free_expire_time_tip'
                    )
                  "
                  placement="top"
                >
                  <svg-icon icon-class="explain" />
                </el-tooltip>
              </div> </span
          ></template>
          <el-date-picker
            v-model="moduleForm.freeExpireTime"
            :disabled="moduleForm.feeOccur"
            style="width: 100%"
            :format="'YYYY-MM'"
            :value-format="'timestamp'"
            type="month"
          />
        </el-form-item>
      </div>
      <el-form-item :label="$t('common.remark')" prop="remark">
        <el-input
          v-model="moduleForm.remark"
          type="textarea"
          maxlength="255"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-tooltip
          v-if="currentServiceOption && currentServiceOption.canRenewal === 1"
          class="item"
          effect="dark"
          :content="this.$t('flycare.contract.auto_renewal_tip')"
          placement="top"
        >
          <el-checkbox
            v-model="autoRenewal"
            style="float: left"
            @change="changeAutoRenewal"
          >
            {{ $t("flycare.contract.auto_renewal") }}
          </el-checkbox>
        </el-tooltip>
        <el-button text @click="closeDialog">{{ $t("common.cancel") }}</el-button>
        <el-button
          v-permission="{ permission: '10401000.MANAGE' }"
          type="primary"
          @click="addModuleInfo"
          >{{ $t("common.confirm") }}</el-button
        >
      </span></template
    >
  </el-dialog>
</template>
<script>
import { findPlatBillingService } from "@/api/module";
import { toTenYMD } from "@/utils/index";
import moment from "moment";
export default {
  data() {
    var priceValidator = (rule, value, callback) => {
      var reg = new RegExp(/^[0-9]+(\.[0-9]{1,4})?$/);
      if (!value) {
        return callback(new Error(this.$t("modules.contract.price_require")));
      }
      if (value && value !== "") {
        if (!reg.test(value)) {
          return callback(new Error(this.$t("modules.contract.price_form_error")));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var serviceAmountValidator = (rule, value, callback) => {
      var reg = new RegExp(/^[0-9]+(\.[0-9]{1,4})?$/);
      if (!value) {
        return callback(new Error(this.$t("modules.contract.price_require")));
      }
      if (value && value !== "") {
        if (!reg.test(value)) {
          return callback(new Error("格式有误"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var serviceQuantityValidator = (rule, value, callback) => {
      var reg = new RegExp(/^[0-9]+(\.[0-9]{1,4})?$/);
      if (!value) {
        return callback(new Error(this.$t("modules.contract.price_require")));
      }
      if (value && value !== "") {
        if (!reg.test(value)) {
          return callback(new Error("格式有误"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var serviceEndTimeValidator = (rule, value, callback) => {
      if (value && value < this.moduleForm.serviceStartTime) {
        callback(new Error(this.$t("flycare.contract.service_expire_time_tip")));
      }
      callback();
    };
    var freeCountValidator = (rule, value, callback) => {
      var reg = new RegExp(/^[0-9]+(\.[0-9]{1,2})?$/);
      if (value || value === 0) {
        if (!reg.test(value)) {
          return callback(new Error("格式有误"));
        } else {
          callback();
        }
      } else {
        callback(new Error());
      }
    };
    var serviceStartTimeValidator = (rule, value, callback) => {
      callback();
    };
    return {
      dialogTitle: "",
      platOptions: [],
      currentPlatOption: {
        platCode: "",
        billingServiceList: [],
      },
      timeQuickSelect: [],
      currentServiceOption: null,
      allowFreeNum: false,
      isEdit: false,
      autoRenewal: false,
      moduleForm: {
        contractDetailUuid: "",
        platCode: "",
        moduleCode: "",
        billingServiceCode: "",
        statisticMethodCode: "",
        currency: "USD",
        price: "",
        freeNum: 0,
        serviceStartTime: moment().startOf("month").unix() * 1000,
        serviceEndTime: null,
        remark: "",
        serviceAmount: null,
        serviceQuantity: null,
        serviceQuantityUnit: null,
        freeExpireTime: null,
        priceUnit: "",
        autoRenewal: 0,
      },
      addModuleRules: {
        billingCycle: [
          {
            required: true,
            message: this.$t("modules.contract.module_require"),
            trigger: "blur",
          },
        ],
        platCode: [
          {
            required: true,
            message: this.$t("modules.contract.platform_require"),
            trigger: "change",
          },
        ],
        billingServiceCode: [
          {
            required: true,
            message: this.$t("modules.contract.statistic_require"),
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            message: this.$t("modules.contract.price_require"),
            trigger: "blur",
          },
          {
            validator: priceValidator,
            trigger: "blur",
          },
        ],
        serviceAmount: [
          {
            required: true,
            message: this.$t("modules.contract.service_amount_require"),
            trigger: "blur",
          },
          {
            validator: serviceAmountValidator,
            message: this.$t("modules.contract.service_amount_format_error"),
            trigger: "blur",
          },
        ],
        serviceQuantity: [
          {
            required: true,
            message: this.$t("modules.contract.service_quantity_require"),
            trigger: "blur",
          },
          {
            validator: serviceQuantityValidator,
            message: this.$t("modules.contract.service_quantity_format_error"),
            trigger: "blur",
          },
        ],
        serviceStartTime: [
          {
            validator: serviceStartTimeValidator,
            trigger: "change",
          },
        ],
        serviceEndTime: [
          {
            validator: serviceEndTimeValidator,
            trigger: "change",
          },
        ],
        freeNum: [
          {
            required: true,
            message: this.$t("modules.contract.free_count_require"),
            trigger: "blur",
          },
          {
            validator: freeCountValidator,
            message: this.$t("modules.contract.free_count_error"),
          },
        ],
        freeExpireTime: [
          {
            required: true,
            message: this.$t("modules.contract.free_expire_time_require"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 获取platCode
    getPlatService() {
      findPlatBillingService()
        .then((res) => {
          this.platOptions.length = 0;
          for (let i = 0; i < res.length; i++) {
            const billingServiceList = [];
            for (let j = 0; j < res[i].billingServiceList.length; j++) {
              const item = res[i].billingServiceList[j];
              const service = {
                value: item.billingServiceCode,
                label: item.billingServiceName,
                allowFreeNum: item.allowFree,
                freeExpireFlag: item.freeExpireFlag,
                unit: item.serviceAmountUnit,
                expireFlag: item.expireFlag,
                billingType: item.billingType,
                serviceQuantityUnit: item.serviceQuantityUnit,
                startTimeRequire: item.startTimeRequire,
                canRenewal: item.canRenewal,
              };
              billingServiceList.push(service);
            }
            const temp = {
              value: res[i].platCode,
              label: res[i].platCode,
              billingServiceList: billingServiceList,
            };
            this.platOptions.push(temp);
          }
          if (this.moduleForm.platCode) {
            this.currentPlatOption = this.platOptions.filter(
              (item) => item.value === this.moduleForm.platCode
            )[0];
          }
          if (this.moduleForm.billingServiceCode) {
            this.currentServiceOption = this.currentPlatOption.billingServiceList.filter(
              (item) => item.value === this.moduleForm.billingServiceCode
            )[0];
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    serviceEndTimeValidator(rule, value, callback) {
      if (this.formItemRequired("serviceEndTime") && !value) {
        callback(new Error(this.$t("flycare.contract.service_expire_time_require")));
      }
      if (value && value < this.moduleForm.serviceStartTime) {
        callback(new Error(this.$t("flycare.contract.service_expire_time_tip")));
      }
      callback();
    },
    formItemRequired(prop) {
      if (this.currentServiceOption) {
        if (prop === "serviceStartTime") {
          return this.currentServiceOption.startTimeRequire === 0;
        }
        if (prop === "serviceEndTime") {
          return this.currentServiceOption.startTimeRequire === 0;
        }
      } else {
        return false;
      }
    },
    getTimeQuickSelectOption() {
      this.timeQuickSelect = [];
      for (let i = 0; i <= 2; i++) {
        const tmp = moment().startOf("month").add(i, "month");
        this.timeQuickSelect.push({
          timeStr: tmp.format("YYYY-MM"),
          timestamp: tmp.unix(),
        });
      }
    },
    changeAutoRenewal() {
      if (this.isEdit) {
        const params = {
          contractModuleId: this.moduleForm.contractModuleId,
          autoRenewal: this.autoRenewal ? 1 : 0,
        };
        this.$emit("updateAutoRenewal", params);
      }
    },
    changeServiceStartTime(val) {
      if (val) {
        if (this.formItemShow("serviceEndTime")) {
          this.moduleForm.serviceEndTime =
            moment(val).startOf("month").add(12, "month").subtract(1, "day").unix() *
            1000;
        }
        if (this.formItemShow("freeExpireTime")) {
          this.moduleForm.freeExpireTime =
            moment(val).startOf("month").add(12, "month").subtract(1, "day").unix() *
            1000;
        }
      } else {
        this.moduleForm.serviceEndTime = "";
      }
    },
    changeFreeNum(val) {
      console.log(val);
      if (val) {
        if (this.formItemShow("freeExpireTime")) {
          if (this.moduleForm.serviceStartTime) {
            this.moduleForm.freeExpireTime =
              moment(this.moduleForm.serviceStartTime)
                .startOf("month")
                .add(12, "month")
                .subtract(1, "day")
                .unix() * 1000;
          }
        }
      }
    },
    quickSelectStartTime(time) {
      this.moduleForm.serviceStartTime = time.timestamp * 1000;
      this.$refs["moduleForm"].validateField("serviceStartTime");
      this.$refs["moduleForm"].validateField("serviceEndTime");
      this.changeServiceStartTime(this.moduleForm.serviceStartTime);
    },
    formItemDisabled(prop) {
      if (prop === "serviceEndTime") {
        return (
          this.currentServiceOption &&
          this.currentServiceOption.unit === "USD_YEAR" &&
          this.moduleForm.feeOccur
        );
      }
    },
    processParams() {
      this.moduleForm.serviceStartTime = this.moduleForm.serviceStartTime / 1000;
      this.moduleForm.statisticMethodCode = this.currentServiceOption.statisticMethodCode;
      this.moduleForm.serviceQuantityUnit = this.currentServiceOption.serviceQuantityUnit;

      if (this.moduleForm.serviceEndTime) {
        this.moduleForm.serviceEndTime = moment(this.moduleForm.serviceEndTime)
          .endOf("month")
          .unix();
      }
      if (this.moduleForm.freeExpireTime) {
        this.moduleForm.freeExpireTime = moment(this.moduleForm.freeExpireTime)
          .endOf("month")
          .unix();
      }
      if (this.autoRenewal) {
        this.moduleForm.autoRenewal = 1;
      }
      if (this.currentServiceOption.startTimeRequire === -1) {
        delete this.moduleForm.serviceStartTime;
      }
    },
    addModuleInfo() {
      this.$refs["moduleForm"].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            delete this.moduleForm.creTime;
            this.$confirm(this.$t("tip_content.edit_module"), "", {
              confirmButtonText: this.$t("common.confirm"),
              cancelButtonText: this.$t("common.cancel"),
              type: "warning",
            })
              .then(() => {
                this.processParams();
                this.$emit("editModule", { ...this.moduleForm });
                this.closeDialog();
              })
              .catch(() => {});
          } else {
            this.processParams();
            this.$emit("addModule", { ...this.moduleForm });
            this.closeDialog();
          }
        }
      });
    },
    formItemShow(prop) {
      if (!this.currentServiceOption) {
        return false;
      }
      if (prop === "serviceStartTime") {
        return this.currentServiceOption.startTimeRequire !== -1;
      }
      if (prop === "serviceQuantity") {
        return (
          this.currentServiceOption.serviceQuantityUnit === "MONTH" ||
          this.currentServiceOption.serviceQuantityUnit === "LICENSE" ||
          this.currentServiceOption.serviceQuantityUnit === "TIME"
        );
      }
      if (prop === "serviceAmount") {
        return this.currentServiceOption.billingType === "ONCE";
      }
      if (prop === "price") {
        return this.currentServiceOption.billingType === "MONTH";
      }
      if (prop === "serviceEndTime") {
        return this.currentServiceOption.expireFlag === 1;
      }
      if (prop === "freeNum") {
        return this.currentServiceOption.allowFreeNum === 1;
      }
      if (prop === "freeExpireTime") {
        return (
          this.moduleForm.freeNum &&
          this.moduleForm.freeNum > 0 &&
          this.currentServiceOption.freeExpireFlag === 1
        );
      }
      return false;
    },
    changePlateCode(val) {
      this.currentPlatOption = this.platOptions.filter((item) => item.value === val)[0];
      console.log(this.currentPlatOption);
      this.moduleForm.moduleCode = "";
      this.moduleForm.billingServiceCode = "";
      this.currentServiceOption = null;
    },
    changeStatisticMethod(val) {
      this.currentServiceOption = this.currentPlatOption.billingServiceList.filter(
        (item) => item.value === val
      )[0];
      this.$refs.moduleForm.clearValidate([
        "serviceAmount",
        "serviceQuantity",
        "serviceStartTime",
        "serviceEndTime",
        "freeNum",
        "freeExpireTime",
        "price",
      ]);
      if (this.formItemShow("serviceStartTime")) {
        this.moduleForm.serviceStartTime = moment().startOf("month").unix() * 1000;
        this.changeServiceStartTime(this.moduleForm.serviceStartTime);
      }
      console.log(this.currentServiceOption);
    },
    closeDialog() {
      this.$refs.moduleForm.resetFields();
      this.currentServiceOption = null;
      this.$emit("update:model-value", false);
      this.moduleForm = {
        contractDetailUuid: "",
        platCode: "",
        moduleCode: "",
        billingServiceCode: "",
        statisticMethodCode: "",
        currency: "USD",
        price: "",
        freeNum: 0,
        serviceStartTime: null,
        serviceEndTime: null,
        remark: "",
        serviceAmount: null,
        serviceQuantity: null,
        serviceQuantityUnit: null,
        freeExpireTime: null,
        priceUnit: "",
      };
    },
    openDialog(moduleInfo, isEdit) {
      this.getTimeQuickSelectOption();
      console.log(moduleInfo);
      console.log(isEdit);
      if (isEdit) {
        this.isEdit = isEdit;
        this.dialogTitle = this.$t("modules.contract.edit_module");
        this.moduleForm = moduleInfo;
        this.autoRenewal = this.moduleForm.autoRenewal === 1;
        if (this.moduleForm.serviceStartTime) {
          this.moduleForm.serviceStartTime = this.moduleForm.serviceStartTime * 1000;
        } else {
          this.moduleForm.serviceStartTime = "";
        }
        if (this.moduleForm.freeExpireTime) {
          this.moduleForm.freeExpireTime = this.moduleForm.freeExpireTime * 1000;
        } else {
          this.moduleForm.freeExpireTime = "";
        }
        if (this.moduleForm.serviceEndTime) {
          this.moduleForm.serviceEndTime = this.moduleForm.serviceEndTime * 1000;
        } else {
          this.moduleForm.serviceEndTime = "";
        }
        console.log(this.moduleForm);
      } else {
        this.isEdit = null;
        this.dialogTitle = this.$t("modules.contract.add_module");
        console.log(this.moduleForm);
      }
      this.$nextTick(() => {
        this.getPlatService();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep #priceInput {
  .el-select .el-input__inner,
  el-input-group__append {
    border-radius: 0;
  }
}
.service_tip {
  height: auto;
  width: 100%;
  line-height: normal;
  white-space: normal;
  margin-top: 5px;
}
</style>
